<template>
  <view class="page-container flex_header_main whov">
    <!-- <view class="page-container flex_header_main whov" :style="{ paddingTop: statusBarHeight + 'px' }"> -->
    <view class="header flex_header">
      <TitleTime :title="detail.pointName || '智能寄存柜'" :deviceId="deviceId" v-if="deviceId" />
    </view>

    <view class="flex_main wrapper" style="width: 100%">
      <view class="flex_left_right" style="align-items: stretch; width: 100%; padding: 0 5%">
        <view class="qrcode-card" style="margin-right: 140rpx">
          <view class="sm_qb">扫码存/取包</view>
          <view class="qrcode-container">
            <view class="qrcode-bg">
              <image class="qrcode-img"  :src="getPlatformInfo().baseUrl + detail.logoQrCode" mode="widthFix" alt="寄存柜二维码" v-if="detail.logoQrCode" />
            </view>
          </view>
          <view class="device-info">
            <text class="device-id">设备编号: {{ detail.counterId }}</text>
            <text class="device-location">{{ detail.counterAlias }}</text>
          </view>
        </view>

        <view class="function-card" style="flex: 1">
          <view class="usage-guide" style="flex: 1">
            <view class="passwort_text"> 免费寄存 </view>
            <ul class="guide-list">
              <li class="guide-item" v-for="(rule, i) in rules" :key="i">
                <text class="guide-text">{{ i + 1 }}. {{ rule }}</text>
              </li>
            </ul>
          </view>

          <view class="function-buttons flex_left_right" style="gap: 36rpx">
            <view class="func-btn pick-btn flex_right" @click="handlePasswordPick('3')">
              <view class="btn-text">密码取包</view>
              <view class="btn-text_dis">取走物品</view>
            </view>
            <view class="func-btn open-btn flex_right" @click="handleMidOpen">
              <view class="btn-text">中途开门</view>
              <view class="btn-text_dis">临时存取</view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <view class="footer flex_footer">
      <text class="footer-text">贵重物品请随身携带，如有遗失，概不负责.</text>
      <text class="footer-text">{{ version }}</text>
    </view>
  </view>
</template>

<script setup lang="ts">
  import { ref, onMounted, onUnmounted } from 'vue'
  import TitleTime from '@/components/TitleTime.vue'
  import { getDeviceInfo, updateVersion } from '@/api/comm'
  import { getPlatformInfo } from '@/utils/platform'
  import { onHide, onLoad, onShow } from '@dcloudio/uni-app'
  import { useFontSize } from '@/utils/fontSizeRootSetting'
  const detail = ref<any>({})
  const deviceId = ref('')
  const version = ref<any>('V1.0.1')
  const { cleanup } = useFontSize()
  // 轮询与并发控制
  const pollTimer = ref<number | null>(null)
  const isFetching = ref(false)

  onUnmounted(cleanup)
  const rules = [`当日${detail.value.hour || '24'}时前请取走所有物品`, '扫码需支付押金，避免柜门无效占用', '结束寄存后押金自动退还，请确认关好柜门']

  const handlePasswordPick = (status: string) => {
    uni.navigateTo({ url: `/pages/index/baoguo?status=${status}&deviceId=${deviceId.value}&pointName=${detail.value.pointName}` })
  }

  const handleMidOpen = () => {
    // uni.showModal({
    //   title: '中途开门',
    //   content: '继续使用将持续计时，确认要开门吗？',
    //   confirmText: '确认',
    //   cancelText: '取消',
    //   success: ({ confirm }) => {
    //     if (confirm) {
    handlePasswordPick('2')
    // }
    //   },
    // })
  }

  onLoad((options: any) => {
    let id = options.zngdeviceId
    if (!id && typeof window !== 'undefined') {
      const params = new URLSearchParams(window.location.search)
      id = params.get('zngdeviceId')
      version.value = params.get('version') || 'V1.0.1'
    }
    deviceId.value = id || '198'
  })
  onShow(async () => init())
  // onMounted(async () => init())
  const init = async () => {
    if (!deviceId.value) return
    if (isFetching.value) return
    try {
      isFetching.value = true
      // 可根据需要保留或移除调试toast
      // uni.showToast({ title: '设备ID：' + deviceId.value, icon: 'none', duration: 2000 })
      const result = await getDeviceInfo(deviceId.value)
      if (result?.data?.pageDataObj) {
        // 成功拿到数据，赋值并停止可能存在的轮询
        detail.value = result.data.pageDataObj
        stopPolling()
      } else {
        // 未拿到数据，则启动轮询（若尚未启动）
        startPolling()
      }
    } catch (e) {
      // 请求异常时也启用轮询以便自动重试
      console.error('init error', e)
      startPolling()
    } finally {
      isFetching.value = false
    }
  }
  const startPolling = () => {
    if (pollTimer.value) return
    pollTimer.value = setInterval(() => {
      if (!isFetching.value) init().catch(() => {})
    }, 5000) as unknown as number
  }
  const stopPolling = () => {
    if (pollTimer.value) {
      clearInterval(pollTimer.value)
      pollTimer.value = null
    }
  }
  // 页面隐藏/切换时停止轮询
  onHide(() => {
    stopPolling()
  })

  // 组件卸载时确保清理
  onUnmounted(() => {
    stopPolling()
    cleanup()
  })
</script>

<style scoped leng="scss">
  .function-card {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-content: space-between;
  }
  .page-container {
    background-color: #ffffff;
    color: #333;
    min-height: 100vh;
  }

  .qrcode-card {
    background-color: #098e00;
    border-radius: 32rpx;
    padding: 48rpx 80rpx;
  }

  .qrcode-container {
    display: flex;
    justify-content: center;
    margin-bottom: 36rpx;
  }

  .qrcode-bg {
    background-color: #fff;
    border-radius: 20rpx;
    width: 1000rpx !important;
    height: 1000rpx !important;
  }

  .qrcode-img {
    width: 100% !important;
    height: 100% !important;
    border-radius: 12rpx;
  }

  .device-info {
    text-align: center;
    padding: 10rpx;
    border-radius: 16rpx;
  }

  .device-id {
    display: block;
    font-size: 64rpx;
    color: #ffffff;
  }

  .device-location {
    font-size: 54rpx;
    color: #ffffff;
  }
  .func-btn {
    text-align: center;
    padding: 20rpx;
    border-radius: 22rpx;
    color: #ffffff;
    padding: 36rpx 100rpx;
  }
  .pick-btn {
    background: linear-gradient(270deg, #f99f55 0%, #f55535 100%);
    border-radius: 28rpx;
  }

  .open-btn {
    background: linear-gradient(270deg, #58b5ec 0%, #0065f2 100%);
    border-radius: 28rpx;
  }

  .btn-text {
    font-size: 84rpx;
    font-weight: 600;
  }
  .btn-text_dis {
    font-size: 56rpx;
  }

  .guide-title {
    display: block;
    font-size: 54rpx;
    color: #1565c0;
    margin-bottom: 28rpx;
    font-weight: 600;
  }

  .guide-list {
    list-style: none;
  }

  .guide-item {
    line-height: 80rpx;
  }

  .guide-item:last-child {
    margin-bottom: 0;
  }

  .guide-icon {
    margin-top: 8rpx;
    flex-shrink: 0;
  }

  .guide-text {
    font-size: 78rpx;
    line-height: 140rpx;
    color: #000000;
  }

  .footer-text {
    font-size: 48rpx;
    color: #c28b00;
    line-height: 100rpx;
  }

  .footer {
    width: 90%;
    margin: 0 auto;
    margin-bottom: 64rpx;
    padding: 6rpx 100rpx;
    background-color: #fff3e0;
    border-radius: 20rpx;
    display: flex;
    justify-content: space-between;
  }
  .sm_qb {
    font-weight: 700;
    font-size: 96rpx;
    text-align: center;
    color: #ffffff;
    margin-bottom: 20rpx;
  }
  .passwort_text {
    font-size: 300rpx;
    color: #076bf2;
  }
</style>
